<?php

namespace Wechat\Controller;

class UserCenterController extends CommonController {

    /**
     * 病例资料
     */
    public function myInfo() {

        $categoryId = $_REQUEST["categoryId"];

        if(!isNullOrEmpty($categoryId)) {
            $this->customer["category_id"] = $categoryId;
        }

        if($this->customer["valid"] != 1) {
            $this->customer["nickname"] = "";
        }

        $ownCategory = D("Category")->queryById($this->customer["category_id"]);

        $this->assign("ownCategory", $ownCategory);
        $this->assign("info", $this->customer);
        $this->display("updateInfo");
    }

    /**
     * 保存病例资料
     */
    public function updateInfo() {

        $this->customer["nickname"] = I("post.nickname");
        $this->customer["sex"] = I("post.sex");
        $this->customer["birthday"] = I("post.birthday");
        $this->customer["mobile"] = I("post.mobile");
        $this->customer["category_id"] = I("post.categoryId");
        $this->customer["doctor_name"] = I("post.doctorName");
        $this->customer["hospital_name"] = I("post.hospitalName");
        $this->customer["diagnosis"] = I("post.diagnosis");
        $this->customer["city"] = I("post.city");
        if( $this->customer["valid"] != 1){
            $this->customer["point"] += 100;
        }
        $this->customer["valid"] = 1;
        $this->customer["update_time"] = getCurrentDate();
        D("Customer")->updateInfo($this->customer);

        $data["code"] = 200;

        echo json_encode($data);

    }

    /**
     * 个人中心
     */
    public function index() {

        if(isNullOrEmpty($this->customer["birthday"])) {
            $this->customer["birthday"] = "暂无";
        }

        if(isNullOrEmpty($this->customer["sex"])) {
            $this->customer["sex"] = "暂无";
        }

        if(isNullOrEmpty($this->customer["mobile"])) {
            $this->customer["sex"] = "暂无";
        }

        $this->assign("customer", $this->customer);
        $this->display("index");
    }

    /**
     * 我的预约
     */
    public function myBooking() {

        $map["b.customer_id"] = $this->customer["customer_id"];
        $map["b.status"] = 1;

        $list = D("Booking")->alias("b")
            ->join("left join __PRODUCT__ p on p.product_id = b.product_id")
            ->join("left join __SHOP__ s on s.shop_id = b.shop_id")
            ->field("b.*,s.address as shop_address,p.image_url as product_image,p.product_name as product_name")
            ->where($map)
            ->order("booking_id desc")
            ->select();

        $this->assign("list", $list);
        $this->display("myBooking");
    }

    /**
     * 我的活动
     */
    public function myActivity() {

        $map["aj.customer_id"] = $this->customer["customer_id"];
        $map["aj.status"] = C("ACTIVITY_JOIN_STATUS.END_PAY");

        $list = D("ActivityJoin")->alias("aj")
            ->join("left join __ACTIVITY__ a on a.activity_id = aj.activity_id")
            ->where($map)
            ->field("a.*")
            ->order("a.activity_id desc")
            ->select();

        foreach ($list as &$item) {
            $item["day"] = date("m月d日", strtotime($item["begin_time"]));
            $item["time"] = date("H:i", strtotime($item["begin_time"]))
                ."-".date("H:i", strtotime($item["end_time"]));
        }

        $this->assign("list", $list);
        $this->display("myActivity");

    }

    /**
     * 我的预约
     */
    public function myPayment() {

        $map["pm.customer_id"] = $this->customer["customer_id"];
        $map["pm.status"] = 1;

        $list = D("Payment")->queryForList(null, $map);

        $this->assign("list", $list);
        $this->display("myPayment");
    }

    /**
     * 我的订单
     */
    public function myOrder() {
        $this->assign("status", $_REQUEST["status"]);
        $this->display("myOrder");
    }

    /**
     * 订单列表
     */
    public function myOrderList() {

        $status = I("post.status");

        if(!isNullOrEmpty($status)) {
            $map["o.status"] = $status;
        }

        $map["o.customer_id"] = $this->customer["customer_id"];

        $list = D("Order")->alias("o")
            ->join("left join __PRODUCT__ p on p.product_id = o.product_id")
            ->where($map)
            ->order("o.order_id desc")
            ->field("o.*,p.price as single_price,p.image_url,p.product_name, p.group_status, p.group_price")
            ->select();

        foreach($list as &$item) {
            $item["measure_data"] = json_decode(html_entity_decode($item["measure_data"]) ,true);
        }

        echo json_encode($list);
    }

    /**
     * 支付页
     */
    public function payInfo() {

        $id = $_REQUEST["id"];

        if(strstr($id, '_')){
            //如果id以"_"开头
            $map["pm.payment_id"] = substr($id,1);
            $map["pm.customer_id"] = $this->customer["customer_id"];

            $payment = D("Payment")->alias("pm")
                ->where($map)
                ->field("pm.*")
                ->find();

            if(isNullOrEmpty($payment)) {
                $this->redirect(U("userCenter/index"));
            }

            $pay = D("Pay")->queryById($payment["pay_id"]);

            if($payment["status"] != C("ORDER_STATUS.WAITING_PAY")) {
                $this->redirect(U("userCenter/myPayment"));
            }
            $this->assign("linkUrl", "/wechat/userCenter/myPayment");
        }elseif(strstr($id, '-')){
            //如果id以"-"开头
            $map["qo.quick_order_id"] = substr($id,1);
            $map["qo.customer_id"] = $this->customer["customer_id"];

            $quickOrder = D("QuickOrder")->alias("qo")
//                ->join("left join __FINISHED_PRODUCT__ fp on fp.finished_product_id = qo.finished_product_id")
                ->where($map)
                ->field("qo.*")
                ->find();

            if(isNullOrEmpty($quickOrder)) {
                $this->redirect(U("finishedProduct"));
            }

            $pay = D("Pay")->queryById($quickOrder["pay_id"]);

            if($quickOrder["status"] != -2) {
                $this->redirect(U("finishedProduct/quickOrderList"));
            }
            $this->assign("linkUrl", "/wechat/finishedProduct/quickOrderList");
        }elseif(strstr($id, 'OTS')){
            //如果id以"OTS"开头
            $map["fo.finished_order_no"] = $id;
            $map["fo.employee_id"] = $this->customer["customer_id"];

            $finishedOrder = D("FinishedOrder")->alias("fo")
//                ->join("left join __FINISHED_PRODUCT__ fp on fp.finished_product_id = qo.finished_product_id")
                ->where($map)
                ->field("fo.*")
                ->find();

            if(isNullOrEmpty($finishedOrder)) {
                $this->redirect(U("finishedProduct"));
            }

            $pay = D("Pay")->queryById($finishedOrder["pay_id"]);

            if($finishedOrder["status"] != -5) {
                $this->redirect(U("finishedProduct/orderList"));
            }
            $this->assign("linkUrl", "/wechat/finishedProduct/orderList");
        }else{//如果id不以"_"和"-"开头
            $map["o.order_id"] = $id;
            $map["o.customer_id"] = $this->customer["customer_id"];
            $this->assign("linkUrl", "/wechat/userCenter/myOrder?status=0");
            $order = D("Order")->alias("o")
                ->join("left join __PRODUCT__ p on p.product_id = o.product_id")
                ->where($map)
                ->field("o.*,p.price as single_price,p.image_url,p.product_name")
                ->find();

            if(isNullOrEmpty($order)) {
                $this->redirect(U("userCenter/index"));
            }

            $pay = D("Pay")->queryById($order["pay_id"]);

            if($order["status"] != C("ORDER_STATUS.WAITING_PAY")) {
                $this->redirect(U("userCenter/myOrder?status=0"));
            }
            $this->assign("linkUrl", "/wechat/userCenter/myOrder?status=0");
        }


        //支付相关
        $arr = array(
            'appid' => C('appid'),
            'mch_id' => C('mch_id'),
            'nonce_str' => $this->createNoncestr(),
            //'sign' => '',	//签名
            'body' => "希卫康产品购买",
            'out_trade_no' => $pay['out_trade_no'], //订单号
            'total_fee' => $pay['money'] * 100, //金额
            'spbill_create_ip' => get_client_ip(),
            'notify_url' => 'http://'.$_SERVER['HTTP_HOST'].'/Wechat/Api/handlePayOrder', //通知地址
            'trade_type' => 'JSAPI',
            'openid' => $this->customer['openid'],
        );

        $arr['sign'] = $this->getSign($arr);  //签名

        $post = curl('https://api.mch.weixin.qq.com/pay/unifiedorder', $this->arrayToXml($arr));

        $arr2 = $this->xmlToArray($post);

        $jsApiObj["appId"] = C('appid');
        $timeStamp = time();
        $jsApiObj["timeStamp"] = "$timeStamp";
        $jsApiObj["nonceStr"] = $this->createNoncestr();
        $jsApiObj["package"] = "prepay_id=" . $arr2['prepay_id'];
        $jsApiObj["signType"] = "MD5";
        $jsApiObj["paySign"] = $this->getSign($jsApiObj);

        //$order["qrcode"] = "http://xwk-file.oss-cn-qingdao.aliyuncs.com/Home/IowaBraceQr".$order["number"].".jpg";

        $this->assign("pay", $pay);
        $this->assign("webarr", $jsApiObj);
        $this->assign("appId", C("appid"));
        $this->assign("config", $this->signature());

        $this->display("payInfo");

    }


    /**
     * 我的订单详情
     */
    public function orderInfo() {

        $id = $_REQUEST["id"];

        $map["o.order_id"] = $id;
        $map["o.customer_id"] = $this->customer["customer_id"];

        $order = D("Order")->alias("o")
            ->join("left join __PRODUCT__ p on p.product_id = o.product_id")
            ->where($map)
            ->field("o.*,p.price as single_price,p.image_url,p.product_name")
            ->find();

        if(isNullOrEmpty($order)) {
            $this->redirect(U("userCenter/index"));
        }

        $pay = D("Pay")->queryById($order["pay_id"]);

        if($order["status"] == C("ORDER_STATUS.WAITING_PAY")) {

            //支付相关
            $arr = array(
                'appid' => C('appid'),
                'mch_id' => C('mch_id'),
                'nonce_str' => $this->createNoncestr(),
                //'sign' => '',	//签名
                'body' => "希卫康产品购买",
                'out_trade_no' => $pay['out_trade_no'], //订单号
                'total_fee' => $pay['money'] * 100, //金额
                'spbill_create_ip' => get_client_ip(),
                'notify_url' => 'http://'.$_SERVER['HTTP_HOST'].'/Wechat/Api/handlePayOrder', //通知地址
                'trade_type' => 'JSAPI',
                'openid' => $this->customer['openid'],
            );

            $arr['sign'] = $this->getSign($arr);  //签名

            $post = curl('https://api.mch.weixin.qq.com/pay/unifiedorder', $this->arrayToXml($arr));

            $arr2 = $this->xmlToArray($post);

            $jsApiObj["appId"] = C('appid');
            $timeStamp = time();
            $jsApiObj["timeStamp"] = "$timeStamp";
            $jsApiObj["nonceStr"] = $this->createNoncestr();
            $jsApiObj["package"] = "prepay_id=" . $arr2['prepay_id'];
            $jsApiObj["signType"] = "MD5";
            $jsApiObj["paySign"] = $this->getSign($jsApiObj);

            $this->assign("webarr", $jsApiObj);
            $this->assign("appId", C("appid"));
            $this->assign("config", $this->signature());
        }

        $this->assign("pay", $pay);
        $this->assign("info", $order);
        $this->display("orderInfo");

    }

    public function about() {

        $map["type"] = "about";

        $content = D("Content")->where($map)->find();

        $this->assign("content", $content);

        $this->display("about");

    }

    public function photo() {

        $map["type"] = "photo";

        $content = D("Content")->where($map)->find();

        $this->assign("content", $content);

        $this->display("photo");

    }

    public function team() {

        $map["type"] = "team";

        $content = D("Content")->where($map)->find();

        $this->assign("content", $content);

        $this->display("team");

    }

    /**
     * 留言
     */
/*
    public function messagebox() {
        $customerId = $this->customer["customer_id"];

        $messageMap["customer_id"] = $customerId;
        $messageMap["day"] = date("Y-m-d");
        $messagebox = D("Messagebox")->queryByMap($messageMap);

        $ownProduct = D("Product")->queryById($messagebox["product_id"]);

        $this->assign("customerId", $customerId);
        $this->assign("ownProduct", $ownProduct);
        $this->assign("info", $messagebox);
        $this->display("messagebox");

    }
*/
    /**
     * 提交留言
     */
/*
    public function updateMessagebox() {

        $messagebox = D("Messagebox")->queryById(I("post.messageId"));

        $messagebox["customer_id"] = I("post.customerId");
        $messagebox["product_id"] = I("post.productId");
        $messagebox["day"] = date("Y-m-d");
        $messagebox["create_time"] = getCurrentDate();
        $messagebox["number"] = I("post.number");
        $messagebox["city"] = I("post.city");
        $messagebox["message_content"] = I("post.messageContent");
        $messagebox["status"] = C("MESSAGEBOX_STATUS.WAITING_REPLY");

        $messageboxId = $messagebox["messagebox_id"];
        if(!isNullOrEmpty($messageboxId)){
            D("Messagebox")->updateInfo($messagebox);
        }else{
            $messageboxId = D("Messagebox")->add($messagebox);
        }

        //推送预约信息到管理员
        $notifyData["url"] = "http://".C('WEB_HOST')."/wechat/messagebox/viewnotify/id/" . $messageboxId;
        $notifyData["first"] = "收到患者留言，请通知相关销售。";
        $notifyData["keyword1"] = "产品：【" . I("post.productName") . "】。";
        $notifyData["keyword2"] = $messagebox["message_content"];
        if(!isNullOrEmpty($messagebox["diagnosis"])){
            $notifyData["keyword2"] .= "；症状或医生诊断：【" . $messagebox["diagnosis"] . "】";
        }
        $notifyData["keyword3"] = $messagebox["create_time"];
        $notifyData["remark"] = "电话：【" . $messagebox["number"] . "】，所在城市：【" . $messagebox["city"] . "】";
        if(!isNullOrEmpty($messagebox["wechatid"])){
            $notifyData["remark"] .= "，微信号：【" . $messagebox["wechatid"] . "】";
        }

        $adminRoleArr = array("1","3");
        $openidArray = getNotifyArr($adminRoleArr, "xWk202003270001");
        $openidArray = array_unique($openidArray);
        foreach ($openidArray as $openid) {
            $notifyData["openid"] = $openid;
            messageboxNotify($notifyData);
        }

        $data["code"] = 200;

        echo json_encode($data);

    }
*/

    public function braceFormer() {

        $map["type"] = "braceFormer";

        $content = D("Content")->where($map)->find();

        $this->assign("content", $content);

        $this->display("braceFormer");

    }

    public function employeeInfo() {
//        if($this->customer["valid"] != 1) {
//            $this->customer["nickname"] = "";
//        }
        $customer = $this->customer;
        $employee = D("Admin")->where(array('employee_id'=>$customer["customer_id"]))->find();
        $enterprise = D("Enterprise")->where(array('enterprise_code'=>$employee["enterprise_code"]))->find();
        $allRoleList = D("AdminRole")->select();
        if(isNullOrEmpty($employee["update_time"]) && $employee["granted"] != 1){
            $newEmployee = 1;
        }else{
            $newEmployee = 0;
        }
        $roleName = "";
        $roleList = explode(',', $employee["role"]);
        foreach($allRoleList as $role) {
            if (in_array($role["id"], $roleList)) {
                $roleName.=$role["name"];
                if($role != end($allRoleList)) {
                    $roleName.="，";
                }
            }
        }

        $this->assign("employee", $employee);
        $this->assign("customer", $customer);
        $this->assign("enterprise", $enterprise);
        $this->assign("roleName", $roleName);
        $this->assign("newEmployee", $newEmployee);
        $this->assign("allRoleList", $allRoleList);
        $this->display("employeeInfo");
    }

    public function getEnterprise() {
        $code = I("post.code");
        $map["ep.enterprise_code"] = $code;
        $list = D("Enterprise")->alias("ep")
            ->where($map)
//            ->field("p.product_id,p.product_name,c.is_finished")
            ->find();
        $roleList = explode(',', $list["role_list"]);
        $allRoleList = D("AdminRole")->select();
        $roleName = "";
        foreach($allRoleList as $role) {
            if (in_array($role["id"], $roleList)) {
                $roleName.=$role["name"];
                if($role != end($allRoleList)) {
                    $roleName.=",";
                }
            }
        }
        if(!isNullOrEmpty($list)){
            $list["role_name"] = $roleName;
        }
        echo json_encode($list);

    }

    public function updateEmployeeInfo() {
        $employee = D("admin")->where(array('employee_id'=>I("post.employeeId")))->find();
        $employee["employee_id"] = I("post.employeeId");
        $employee["enterprise_code"] = I("post.enterpriseCode");
        $employee["enterprise_name"] = I("post.enterpriseName");
        $employee["admin_name"] = I("post.adminName");
        $employee["mobile"] = I("post.mobile");
//        $employee["username"] = I("post.username");
//        $employee["password"] = I("post.password");
        $employee["note"] = I("post.note");
        $employee["pre_role"] = I("post.role");
        $employee["update_time"] = getCurrentDate();
        $employee["update_id"] = $this->customer["customer_id"];
        $employee["granted"] = 0;
        $employee["openid"] = $this->customer["openid"];
        $employee["headimgurl"] = $this->customer["headimgurl"];
        $employee["note"] = I("post.note");

        if(!isNullOrEmpty($employee["user_id"])){
            D("admin")->where(array('user_id'=>$employee["user_id"]))->save($employee);
            $notifyData["first"] = "收到【".I("post.enterpriseName")."】企业用户更新信息申请，请审核。";
        }else{
            $employee["create_time"] = getCurrentDate();
            D("admin")->add($employee);
            $notifyData["first"] = "收到【".I("post.enterpriseName")."】企业用户注册信息申请，请审核。";
        }

        $notifyData["keyword1"] = $employee["admin_name"];
        $notifyData["keyword2"] = $employee["mobile"];
        $notifyData["keyword3"] = "企业用户信息更新";
        $notifyData["keyword4"] = "申请部门：";
            $allRoleList = D("AdminRole")->select();
        $enterpriseRoleList = explode(',', I("post.role"));
        foreach($allRoleList as $role){
            if(in_array($role["id"],$enterpriseRoleList)){
                $notifyData["keyword4"].= $role["name"]."；";
            }
        }
        $notifyData["remark"] = I("post.note")."。";
        //发送通知给管理员
//        $adminRoleArr = array("1","7");
//        $openidArray = getNotifyArr($adminRoleArr, I("post.enterpriseCode"));
        $openidArray = getNotifyArrByName("register", I("post.enterpriseCode"));
        foreach ($openidArray as $openid) {
            $notifyData["openid"] = $openid;
            registerNotify($notifyData);
        }
        //发送通知给自己
        $notifyData1["openid"] = $this->customer["openid"];;
        $notifyData1["first"] = "您已提交【".I("post.enterpriseName")."】企业用户注册信息申请，请等待管理员审核。";
        $notifyData1["keyword1"] = $notifyData["keyword4"];
        $notifyData1["keyword2"] = "等待审核";
        $notifyData1["keyword3"] = getCurrentDate();
        progressNotify($notifyData1);

        $data["code"] = 200;
//        $data["msg"] = $mess;
        echo json_encode($data);
    }

}